// pages/news/news.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: app.globalData.url,
    test_url: app.globalData.test_url,
    cardCur: 0,
    swiperList: [{
      id: 0,
      type: 'image',
      src: 'http://a4.qpic.cn/psb?/V10uH3z53mPeWp/KpPK9eWLSWs5VyY7ut3LDMR7c2aVMYrN9sNu6FGwU9M!/b/dL8AAAAAAAAA&ek=1&kp=1&pt=0&bo=gAdYAoAHWAIDR2I!&tl=1&vuin=939682389&tm=1556780400&sce=60-2-2&rf=viewer_4',
      url:"/pages/mine/find/ENGLISH/ENGLISH"
    }, {
      id: 1,
      type: 'image',
        src: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/3aJMH5fYYYLt0IM*7SMLbSS6h12GKtgTHxyV0GsyFxc!/b/dLYAAAAAAAAA&bo=gAdYAgAAAAADN88!&rf=viewer_4',
    }, {
      id: 2,
      type: 'image',
        src: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/113a49EqR8Ot4yKelGTDB3cB4sVgw0vcgxqLri0pyyo!/b/dLgAAAAAAAAA&bo=OARSAQAAAAADJ20!&rf=viewer_4',
    },{
      id:3,
        type: 'image',
        src:'http://a3.qpic.cn/psb?/V10uH3z53mPeWp/wxe0hXLj7*hAkNoW2LmwtcbTBQJHp6Mm1Pac8dFVCq8!/b/dD4BAAAAAAAA&ek=1&kp=1&pt=0&bo=gAdYAoAHWAIDFzI!&tl=1&vuin=939682389&tm=1556784000&sce=60-1-1&rf=viewer_4',
        //url:'/pages/mine/find/answer/index/index'
    }],
    TabCur: 0, //索引type
    scrollLeft: 0,
    items: app.globalData.items,
    list: [
      [],
      [],
      [],
      [],
      [],
      [],
      [],
    ],

    status: false, //搜索状态
    searchContent: "", //搜索内容
    searchResult: [], //搜索结果
    search_isShowMore: false, //搜索结果
    search_isShow: true,
    searchLength: 5,
    isLoad: [false, false, false, false, false, false, false, ], //是否正在加载
    isLoadAll: [false, false, false, false, false, false, false, ], //是否加载全部
    page: [1, 1, 1, 1, 1, 1, 1],
    swiperCurrent:0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    is_show: false,

  },
  //授权反馈
  bindGetUserInfo(e) {
    var that = this;
    that.onLoad()
    if (e.detail.userInfo) {
      console.log(e.detail.userInfo.nickName)
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: app.globalData.url + 'user/code',
            data: {
              code: res.code,
              nick: e.detail.userInfo.nickName,
              avatar: e.detail.userInfo.avatarUrl
            },
            method: "POST",
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              app.globalData.openid = res.data.data.openid //返回openid
              console.log("------openid------")
              console.log(res.data.data)
            }
          })
        }
      })
    }
  },
  toAd(e){
    var that = this
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: that.data.swiperList[e.currentTarget.dataset.id].url,
    })
  },
  /* 文本框聚焦时更改状态*/
  focus: function(e) {
    //console.log(e)
    this.setData({
      status: true,
      search_isShow: true
    })
  },
  /* 文本框失焦时更改状态*/
  blur: function(e) {
    this.setData({
      status: false,
      search_isShow: false,
    })
  },
  //动态搜索
  search: function(e) {
    var key = e.detail.value;
    //console.log(key)
    this.setData({
        searchContent: key,
        searchLength: 5,
        search_isShowMore: false,
      }),
      this.getSearch(key)
  },
  searchNews: function() {
    var that = this
      app.globalData.searchResult = that.data.searchResult
    this.setData({
      searchContent: "",
      searchResult: []
    }),
    wx.navigateTo({
      url: './searchDetail/searchDetail', //跳转页面的路径，可带参数 ？隔开，不同参数用 & 分隔；相对路径，不需要.wxml后缀
      success: function() {}, //成功后的回调；
      fail: function() {}, //失败后的回调；
      complete: function() {} //结束后的回调(成功，失败都会执行)
    })
  },
  //显示更多
  searchMore: function() {
    var that = this
    var length = that.data.searchLength + 5
    if (that.data.searchResult.length <= length) {
      that.setData({
        search_isShowMore: false,
        status: true
      })
    }
    that.setData({
      searchLength: length,
    })

  },

  getNews: function(page, type) {
    var that = this;
    //加载
    var isLoads = that.data.isLoad
    isLoads[type] = true
    that.setData({
      isLoad: isLoads
    })
    wx.request({
      url: app.globalData.url + 'news', // 仅为示例，并非真实的接口地址
      data: {
        page: page,
        type: type
      },
      method: "GET",
      header: {

        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log("------得到数据------")
        console.log(res.data.data)
        var newsList = that.data.list;
        for (var i = 0; i < res.data.data.length; i++) {
          newsList[type].push(res.data.data[i])
        }
        //取消加载
        console.log("------list------")
        var isLoads = that.data.isLoad
        isLoads[type] = false
        //that.data.list[type]= newsList
        that.setData({
          isLoad: isLoads
        })
        console.log(that.data.list)

        //加载全部
        if (res.data.data.length == 0) {
          //显示加载全部
          var isLoadAlls = that.data.isLoadAll
          isLoadAlls[type] = true
          that.setData({
            isLoadAll: isLoadAlls
          })
        } else {
          var pages = that.data.page
          pages[type] = pages[type] + 1
          that.setData({
            list: newsList,
            page: pages
          })

        }
      }
    })
  },
  //获取搜索内容
  getSearch: function(key) {
    var that = this;
    if (key) {
      wx.request({
        url: 'https://api.bangstuhelp.com/news/source/' + key,
        data: {},
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log("------搜索数据-------")
          console.log(res.data.data)
          var result = res.data.data
          that.setData({
            searchResult: result,
          })
          if (result.length > that.data.searchLength) {
            that.setData({
              search_isShowMore: true
            })
          }
        }
      })
    } else {
      that.setData({
        searchResult: {},
      })
    }
  },
  //跳转页面
  toUrl: function(e) {
    console.log(e)
    wx.navigateTo({
      url: './detail/detail?'
    })
  },
  //选择tab
  tabSelect(e) {
    var tc = e.currentTarget.dataset.id
    var that = this
    this.setData({
      TabCur: tc,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
    console.log("------TabCur------"),
      console.log(e.target.dataset.id)
    //如果还没有加载
    if (that.data.page[tc] == 1) {
      that.getNews(that.data.page[tc], tc)
    }
  },
  //选择搜索栏项目
  searchSelect(e) {
    var that = this
    //console.log(e.currentTarget.dataset.id)
    setTimeout(function() {
      that.setData({
        searchContent: "",
        searchResult: {},
        search_isShowMore: false,
      })
      that.toUrl();
    }, 500);

  },
  /**
   * 生命周期函数--监听页面加载
   */
  //初始化
  init(){
    this.setData({
      status: false, //搜索状态
      searchContent: "", //搜索内容
      searchResult: [], //搜索结果
      search_isShowMore: false, //搜索结果
      search_isShow: true,
      searchLength: 5,
      isLoad: [false, false, false, false, false, false, false,], //是否正在加载
      isLoadAll: [false, false, false, false, false, false, false,], //是否加载全部
      page: [1, 1, 1, 1, 1, 1, 1],
      list: [
        [],
        [],
        [],
        [],
        [],
        [],
        [],
      ],
    })
  },
  onLoad: function(options) {
    var that =this
    that.init()
    var typ = this.data.TabCur
    var pag = this.data.page[typ]
    this.getNews(pag, typ)
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
              app.globalData.userInfo = res.userInfo
            }
          })

          that.setData({
            is_show: false
          })
        }
        else {
          that.setData({
            is_show: true
          })
        }
      }
    })
      
    

  },
  //是否注册跳转
  is_register(){
    wx.request({
      url: app.globalData.url + 'user/register/' + app.globalData.openid,
      data: {},
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log('------register------')
        console.log(res.data)
        //未注册
        if(res.data.state == 0)
        {
          wx.navigateTo({
            url: '/pages/mine/information/information'　　// 页面 A
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onLoad()
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    console.log('--------上拉触底-------')
    var that = this;
    var typ = that.data.TabCur
    var pag = that.data.page[typ]
    that.getNews(pag, typ)
    //console.log(pag)
    if (!that.data.isLoadAll[typ]) {
      var pages = that.data.page
      pages[typ] = pag
      that.setData({
        page: pages
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})